/**
 * 
 * This is an attempt to introduce a notification capability to Funf.
 * 
 * This allows a persistent notification to be shown while Funf Manager service is running in the background. 
 * 
 * 
 */
package com.pels.funf.ext.notifications;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Binder;
import android.support.v4.app.NotificationCompat;
import edu.mit.media.funf.FunfManager;
import edu.mit.media.funf.R;
import edu.mit.media.funf.util.StringUtil;

public class FunfManagerWithNotifications extends FunfManager {

	private NotificationManager nManager;
	private NotificationCompat.Builder notificationBuilder = null;
	private final int NOTIFICATION = 007;

	public static final String ENABLED_PIPELINES = "ENABLED_PIPELINES",
			DISABLED_PIPELINES = "DISABLED_PIPELINES";

	@Override
	public void onCreate() {
		super.onCreate();

		// Get notification manager instance
		nManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		showNotification();
	}

	/**
	 * Prepares and issues notification. It assigns a pending intent which holds
	 * a list of pipelines and which are disabled. The intent is used to launch
	 * the settings activity which provides some control for enabling and
	 * disabling pipelines.
	 */
	private void showNotification() {
		// Prepares and dispatches a notification for Funf Manager service

		String notificationContent = "Number of enabled pipelines: "
				+ getPipelines().size();

		Intent intent = new Intent(getApplicationContext(), Settings.class);

		intent.putExtra(ENABLED_PIPELINES,
				StringUtil.join(getPipelines().keySet(), ","));
		intent.putExtra(DISABLED_PIPELINES,
				StringUtil.join(getDisabledPipelineNames(), ","));

		PendingIntent pendingIntent = PendingIntent.getActivity(
				getApplicationContext(), 1, intent,
				PendingIntent.FLAG_CANCEL_CURRENT);

		if (notificationBuilder == null) {
			String notificationTitle = "Funf Manager Service";
			notificationBuilder = new NotificationCompat.Builder(this)
					.setContentTitle(notificationTitle)
					.setSmallIcon(R.drawable.funf_icon).setOngoing(true)
					.setTicker(notificationTitle);
		}
		notificationBuilder.setContentText(notificationContent)
				.setContentIntent(pendingIntent);
		nManager.notify(NOTIFICATION, notificationBuilder.build());
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		nManager.cancel(NOTIFICATION);
	}

	@Override
	public void enablePipeline(String name) {
		super.enablePipeline(name);
		showNotification();
	}

	@Override
	public void disablePipeline(String name) {
		super.disablePipeline(name);
		if (getPipelines().size() == 0) {
			nManager.cancel(NOTIFICATION);
			stopSelf();
		} else {
			showNotification();
		}
//		showNotification();
	}
	
	public class LocalBinder extends Binder {
		public FunfManagerWithNotifications getManager() {
			return FunfManagerWithNotifications.this;
		}
	}
}
